<template>
  <div class="com-container">
    <div id="HuNanBMap" class="com-chart" ref="map_ref"></div>
    <ul class="drawing-panel" v-if="isShowBtn">
      <li class="btn" @click="mapPosition()">位置点图</li>
    </ul>
  </div>
</template>

<script>

export default {
  name: 'HuNanBMap',
  data () {
    return {
      map: null,//百度地图实例
      bounds: null,//区域
      initCenter: {},//初始化中心
      areaColorMap: new Map([
        ['长沙市', '#DD6B66'],
        ['株洲市', '#FDAC94'],
        ['湘潭市', '#9BD4B9'],
        ['衡阳市', '#EA7E53'],
        ['邵阳市', '#F4E57C'],
        ['岳阳市', '#7EB37E'],
        ['常德市', '#73B9BC'],
        ['张家界市', '#7D96BC'],
        ['益阳市', '#9FDE9A'],
        ['郴州市', '#409F02'],
        ['永州市', '#A566C2'],
        ['怀化市', '#EA7CCC'],
        ['娄底市', '#FAC858'],
        ['湘西土家族苗族自治州', '#D5C13B'],
      ]),//地区颜色
      areaHoleMap: new Map(),//名字：区域 缓存
      isShowBtn:false,//按钮是否显示
    }
  },
  mounted () {
    this.init()
    //增加屏幕大小变化监听的事件
    window.addEventListener('resize', this.screenAdapter)
  },
  destroyed () {
    window.removeEventListener('resize', this.screenAdapter)
  },
  methods: {
    screenAdapter () {
      this.init()
    },
    mapPosition () {
      this.$router.push({ path: "/mapPosition" })
    },
    async init () {
      const that = this
      // 百度地图API功能
      var map = new BMapGL.Map('HuNanBMap')    // 创建Map实例
      //设置个性化地图
      map.setMapStyleV2({
        styleId: 'c1da7b4f875a03d348e5815474fbd645'
      })

      map.enableScrollWheelZoom(true)     //开启鼠标滚轮缩放

      map.addEventListener('click', function (e) {
        //鼠标点击处的经纬度
        var pt = e.latlng
        if (that.bounds !== null && !that.isPointInRect(pt, that.bounds)) {
          //初始化
          that.reset()
        } else {
          if (that.bounds !== null) {
            return
          }
          //逆编码
          const geoc = new BMapGL.Geocoder()

          geoc.getLocation(pt, function (rs) {
            console.log(rs)
            if (rs.addressComponents.province !== '湖南省') {
              map.centerAndZoom(that.initCenter, 7)
              that.bounds = null
              return
            }
            // 获取鼠标点击的市级区域
            const currentCity = rs.addressComponents.city
            that.$emit('getCurrentCity', currentCity)
            //绘制边界
            const bd = new BMapGL.Boundary()
            bd.get(currentCity, function (bdrs) {
              const hole = new BMapGL.Polygon(bdrs.boundaries, {
                fillOpacity: 0.8,
                fillColor: that.areaColorMap.get(currentCity),
                strokeColor: '#636566',
                strokeWeight: 4,
                strokeOpacity: 0.5
              })
              that.bounds = hole.getBounds()
              //清除之前的覆盖物
              map.clearOverlays()
              map.addOverlay(hole)
              map.centerAndZoom(that.getCenterPoint(that.bounds), 9)
            })
          })
        }
      })
      map.addEventListener('rightclick', function (e) {
        that.reset()
      })
      const huNan = new BMapGL.Boundary()
      await huNan.get('湖南省', function (bdrs) {
        const hole = new BMapGL.Polygon(bdrs.boundaries, {})
        const huNanBounds = hole.getBounds()
        that.initCenter = that.getCenterPoint(huNanBounds)
        console.log(that.initCenter)
        map.centerAndZoom(that.initCenter, 7)  // 初始化地图,设置中心点坐标和地图级别
        that.map = map
        that.overlayCity()
      })
    },
    reset () {
      if (!this.areaHoleMap) {
        return
      }
      this.map.clearOverlays()
      this.bounds = null
      this.areaHoleMap.forEach((hole) => {
        this.map.addOverlay(hole)
      })
      this.map.centerAndZoom(this.initCenter, 7)
      this.$emit('getCurrentCity', '')
    },
    overlayCity () {
      const that = this
      // 绘制边界
      const bd = new BMapGL.Boundary()
      // 为每个区域绘制颜色
      this.areaColorMap.forEach((color, city) => {
        bd.get(city, function (bdrs) {
          const hole = new BMapGL.Polygon(bdrs.boundaries, {
            fillOpacity: 0.8,
            fillColor: color,
            strokeColor: '#636566',
            strokeWeight: 4,
            strokeOpacity: 0.5
          })
          that.map.addOverlay(hole)
          that.areaHoleMap.set(city, hole)
        })
      })
      that.map.centerAndZoom(that.initCenter, 7)
    },
    /**
     * 判断点是否在矩形内
     * @param {Point} point 点对象
     * @param {Bounds} bounds 矩形边界对象
     * @returns {Boolean} 点在矩形内返回true,否则返回false
     */
    isPointInRect (point, bounds) {
      //检查类型是否正确
      if (
        !(point.toString() === 'Point' || point.toString() === 'LatLng') ||
        !(bounds instanceof BMapGL.Bounds)
      ) {
        return false
      }
      var sw = bounds.getSouthWest() //西南脚点
      var ne = bounds.getNorthEast() //东北脚点
      return (
        point.lng >= sw.lng &&
        point.lng <= ne.lng &&
        point.lat >= sw.lat &&
        point.lat <= ne.lat
      )
    },
    getCenterPoint (bounds) {
      const centerLng = (bounds.maxX + bounds.minX) / 2
      const centerLat = (bounds.maxY + bounds.minY) / 2
      return new BMapGL.Point(centerLng, centerLat)
    }
  }
}
</script>

<style scoped>

#HuNanBMap {
  width: 100%;
  height: 100%;
}
ul li {
  list-style: none;
}

.drawing-panel {
  z-index: 99;
  position: fixed;
  bottom: 3.5rem;
  margin-left: 3rem;
  padding: 1rem 1rem;
  border-radius: .25rem;
  background-color: #fff;
  box-shadow: 0 2px 6px 0 rgba(27, 142, 236, 0.5);
}

.btn {
  width: 90px;
  height: 30px;
  float: left;
  background-color: #fff;
  color: rgba(27, 142, 236, 1);
  font-size: 14px;
  border: 1px solid rgba(27, 142, 236, 1);
  border-radius: 5px;
  margin: 0 5px;
  text-align: center;
  line-height: 30px;
}

.btn:hover {
  background-color: rgba(27, 142, 236, 0.8);
  color: #fff;
}
</style>
